<template>
    <div>
        <!--        :gutter="10"-->
        <el-row v-if="visibleTop" :gutter="10" class="mb8 ml10">
            <div style="position: relative;float: left;align-items: center;display: flex;">
                <slot name="topBefore"></slot>
                <!--                例如-->
                <!--                <template slot="topBefore">-->
                <!--                    <div class="ml5 mr5">-->
                <!--                        采购清单-->
                <!--                    </div>-->
                <!--                如果使用列表名称 按钮要放这里-->
                <!--                <el-col :span="1.5">-->
                <!--                    <aut-button-->
                <!--                        type="primary"-->
                <!--                        icon="el-icon-plus"-->
                <!--                        @click="handleAdd()"-->
                <!--                    >新增</aut-button>-->
                <!--                </el-col>-->
                <!--                </template>-->
            </div>
            <slot name="top"></slot>
            <sks-right-toolbar
                :mainTable="mainTable"
                :showTablePropName.sync="mainTable.showTablePropName"
                :showRefreshButton="showRefreshButton"
                :showTable.sync="mainTable.showTable" :showAllColumnButton="mainTable.showAllColumnButton" :showAllColumn.sync="mainTable.showAllColumn"
                :showSearchButton.sync="mainTable.showSearchButton"
                :showSearch.sync="mainTable.showSearch" @queryTable="refreshTable()">
                <template slot="prefix">
                    <slot name="topPrefix"></slot>
                </template>
            </sks-right-toolbar>
        </el-row>
        <el-table v-if="mainTable.showTable" v-loading="mainTable.loading" :data="mainTable.list"   @selection-change="handleSelectionChange"
                  :height="mainTable.tableHeight"
                  :highlight-current-row="highlightCurrentRow"
                  :row-style="rowStyle"
                  @row-click="rowClickMainTable"
                  :style="tableStyle"
                  :element-loading-text="mainTable.elementLoadingText"
        >
            <el-table-column v-if="mainTable.showCacheChangeFlagColumn" label="" align="center" min-width="25px" :render-header="renderHeaderCacheChangeFlagColumn">
                <template slot-scope="{row}">
                    <template v-if="row.virtualChangeBitFlag==sksUtils.CHANGE_BIT_FLAG.delete">
                        <el-tooltip className="item" effect="dark" content="该行已标识为'删除'" placement="top">
                            <i style="color: red" class="el-icon-delete"></i>
                        </el-tooltip>
                    </template>
                    <template v-else-if="row.virtualChangeBitFlag==sksUtils.CHANGE_BIT_FLAG.add">
                        <el-tooltip className="item" effect="dark" content="该行已标识为'新增'" placement="top">
                            <i style="color: blue" class="el-icon-plus"></i>
                        </el-tooltip>
                    </template>
                    <template v-else-if="row.virtualChangeBitFlag==sksUtils.CHANGE_BIT_FLAG.modify">
                        <el-tooltip className="item" effect="dark" content="该行已标识为'修改'" placement="top">
                            <i style="color: DarkGreen" class="el-icon-edit"></i>
                        </el-tooltip>
                    </template>
                </template>
            </el-table-column>
            <!--        动态列,列显示错位,官方建议增加一个 width为1的列-->
            <!--            <el-table-column width="1"/>-->
            <slot name="tableColumnList-before"></slot>
            <!--
            <template slot="tableColumnList-before" slot-scope="scope">
            </template>
            -->
            <template v-if="mainTable.tableColumnListEnable&&sksUtils.notNullAndNotUndefined(sksUtils.safeGet(mainTable,'tableColumnList'))">
                <!--        <el-table-column>-->
                <!--        {{safeGet(mainTable,'tableColumnList')}}-->
                <!--        </el-table-column>-->
                <!--        动态列,列显示错位,官方建议增加一个 width为1的列-->
                <!--        <el-table-column width="1"></el-table-column>-->
                <template v-for="(item,itemIndex) in mainTable.tableColumnList">
                    <template v-if="sksUtils.strIsEmpty(item.slot)" >
                        <!--                    当表格列项动态显示时，多次刷新，造成渲染时出现列项错乱现象
                                            加上 key="itemIndex"
                        -->
                        <el-table-column
                            :show-overflow-tooltip="sksUtils.ifNull(item.showOverflowTooltip,webListPropPropConfig.showOverflowTooltip)"
                            :className="item.className"
                            :filters="item.filters"
                            :align="item.align||webListPropPropConfig.align" :prop="item.prop"
                            :width="item.width"
                            :min-width="item.minWidth"
                            :label="item.label" v-if="item.visible||mainTable.showAllColumn" :render-header="(h,args)=>renderHeader(h,args,item)">
                            <template slot-scope="scope">
                                <template v-if="item.htmlType=='none'">
                                    <slot :name="`none-${item.prop}`" :row="scope.row" :column="scope.column" :$index="scope.$index" :item="item">
                                    </slot>
                                </template>
                                <template v-else-if="item.htmlType=='parseTimeYmd'">
                                    {{sksUtils.parseTime(sksUtils.safeGet(scope.row,item.prop),'{y}-{m}-{d}')}}
                                </template>
                                <template v-else-if="item.htmlType=='parseTimeMdHm'">
                                    {{sksUtils.parseTime(sksUtils.safeGet(scope.row,item.prop),'{m}-{d} {h}:{i}')}}
                                </template>
                                <template v-else-if="item.htmlType=='parseTimeYmdHm'">
                                    {{sksUtils.parseTime(sksUtils.safeGet(scope.row,item.prop),'{y}-{m}-{d} {h}:{i}')}}
                                </template>
                                <template v-else-if="item.htmlType=='dictFormatObject'">
                                    <!--                                    <div :class="safeGet(scope.row,`${item.prop}.cssClass`)">{{sksUtils.safeGet(scope.row,`${item.prop}.dictLabel`)}}</div>-->
                                    <SksDictLabelTag :dict-data="sksUtils.safeGet(scope.row,`${item.prop}`)"></SksDictLabelTag>
                                </template>
                                <template v-else-if="item.htmlType=='no0InfoYes1Danger'">
                                    <el-tag type="danger" v-if="sksUtils.safeGet(scope.row,item.prop)==1">
                                        是
                                    </el-tag>
                                    <el-tag type="info" v-else>
                                        否
                                    </el-tag>
                                </template>
                                <template v-else-if="item.htmlType=='unFinish0WarningFinish1Success'">
                                    <el-tag type="success" v-if="sksUtils.safeGet(scope.row,item.prop)==1">
                                        已完结
                                    </el-tag>
                                    <el-tag type="warning" v-else>
                                        未完结
                                    </el-tag>
                                </template>
                                <template v-else-if="item.htmlType=='negateNumber'">
                                    {{sksUtils.negateNumber(sksUtils.safeGet(scope.row,item.prop))}}
                                </template>
                                <template v-else-if="item.htmlType=='absNumber'">
                                    {{sksUtils.absNumber(sksUtils.safeGet(scope.row,item.prop))}}
                                </template>
                                <template v-else-if="item.htmlType=='elImageByImgUrl'">
                                    <template v-if="!sksUtils.strIsEmpty(sksUtils.safeGet(scope.row,item.prop))">
                                        <sksImageUseImgUrl v-model="scope.row[item.prop]"/>
                                    </template>
                                </template>
                                <template v-else>
                                    <template v-if="item.textColor=='none'" >
                                        {{sksUtils.safeGet(scope.row,item.prop)}}
                                    </template>
                                    <template v-else>
                                        <div :style="{color: item.textColor}">{{sksUtils.safeGet(scope.row,item.prop)}}</div>
                                    </template>
                                </template>
                            </template>
                        </el-table-column>
                    </template>
                    <template v-else>
                        <slot  :name="'custom-'+item.slot" :item="item" :webListPropPropConfig="webListPropPropConfig" :renderHeader="renderHeader">
                        </slot>
                    </template>
                </template>
            </template>
            <template v-else>
                <slot name="default"></slot>
            </template>
            <slot name="tableColumnList-after"></slot>
        </el-table>

        <el-dialog :close-on-click-modal="true" :title="propTableDialogInfo.title" :visible.sync="propTableDialogInfo.showDialog" width="800px"  append-to-body>
            <SksTablePropTable :item="propTableDialogInfo.data"
                               @showDictDataDialog="(args)=>$emit('showDictDataDialog',args)"
                               @jumpToDictData="(args)=>$emit('jumpToDictData',args)">
            </SksTablePropTable>
        </el-dialog>
    </div>
</template>

<script>


import clipboard from "../../../clipboard";
import {
    deleteFromVueVirtualUUID,
    getIndexByUUIDTable,
    getNewChangeRowList,
    initListVueVirtualUUID, initRowVueVirtualUUID, isNullOrUndefined, mergeFromObject
} from "../../../core";
import {defaultSksTableColumnData, dictFormatOnElTableColumn, rowStyleElTable} from "../../../sks-app-utils";
import {newSksDialogInfo} from "../../../sks-model-utils";


export default {
    name: 'SksCacheTable',
    components:{
    },
    props:{
        //显示刷新按钮
        showRefreshButton: {
            type: Boolean,
            default: false,
        },
        //显示顶部工具条
        visibleTop: {
            type: Boolean,
            default: true,
        },
        tableStyle: [Object,String],
        mainTable:[Object],
        highlightCurrentRow: {
            type: Boolean,
            default: true
        },
        rowStyle:{
            type:  [Object, Function],
            default: ()=>{
                return rowStyleElTable
            }
        },
        tabsFilterValueChange:[Function],

        //自定义拖动排序方法,如果不为空则使用自定义排序方法
        dragSortCustomize:[Function],
    },
    data(){
        return {
            webListPropPropConfig: defaultSksTableColumnData,
            firstInitList: true,

            propTableDialogInfo: mergeFromObject({},newSksDialogInfo(),{
                data:{},
                showDialog: false,
                title: '列表字段属性',
            }),
        }
    },
    watch:{
        "mainTable.list":{
            handler(val){
                initListVueVirtualUUID(this.mainTable.list)
                if(this.mainTable&&this.firstInitList){
                    this.firstInitList=false
                }
            },
            immediate: true,
        }
    },
    methods:{
        //list排序变更等原因,需要重新渲染table
        reRenderTable(){
            //table 用于触发重新渲染table
            this.mainTable.showTable=false
            setTimeout(()=>{
                this.mainTable.showTable=true
                this.initTableDragSort()
            },100)
        },
        initTableDragSort(){
            if(this.mainTable.dragSort) {
                this.$nextTick(() => {
                    const el = this.$refs[this.mainTable.uuid].$el.querySelectorAll(".el-table__body-wrapper > table > tbody")[0];
                    console.log("uuid", this.mainTable.uuid)
                    console.log("el", el)
                    this.mainTable.dragSortTableTmp = Sortable.create(el, {
                        handle: ".allowDrag",
                        onEnd: (evt) => {
                            if (this.dragSortCustomize) {
                                this.dragSortCustomize(evt)
                                return
                            }
                            let list = this.mainTable.list;
                            const targetRow = list.splice(evt.oldIndex, 1)[0];
                            list.splice(evt.newIndex, 0, targetRow);
                            const ids = list.map(item => item[this.mainTable.uniqueId])
                            console.log("list.ids", ids)
                            console.log("list", list)
                            // for (let index in list) {
                            //     list[index][this.mainTable.dragSortPropName] = parseInt(index) + 1;
                            // }
                            // this.$set(this.mainTable,'list',list);
                            this.$emit('dragSort')
                        }
                    });
                })
            }
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.mainTable.selection=selection
            this.mainTable.ids = selection.map(item => item[this.mainTable.uniqueId]);
            this.mainTable.single = selection.length != 1;
            this.mainTable.multiple = !selection.length;
            this.$emit('selectionChangeAfter',selection)
        },

        rowClickMainTable(row){
            this.mainTable.currentRow=row
        },
        refreshTable(){
            this.$emit('refresh')
        },
        addOrUpdateRow(row){
            if(isNullOrUndefined(row.vueVirtualUUID)){
                initRowVueVirtualUUID(row)
            }
            if(isNullOrUndefined(row[this.mainTable.uniqueId])){
                row.virtualChangeBitFlag= this.sksUtils.CHANGE_BIT_FLAG.add
            }else{
                row.virtualChangeBitFlag= this.sksUtils.CHANGE_BIT_FLAG.modify
            }
            let index = getIndexByUUIDTable(this.mainTable.list,row);
            if(index==-1){
                this.mainTable.list.push(row)
                return;
            }
            this.$set(this.mainTable.list, index, row);
        },
        deleteRow(row){
            // console.log("deleteRow",isNullOrUndefined(this.mainTable.uniqueId))
            if(isNullOrUndefined(this.mainTable.uniqueId)){
                deleteFromVueVirtualUUID(this.mainTable.list,row)
                console.warn("initMainTableParam() 未返回 uniqueId ")
                return
            }
            // console.log("deleteRow",isNullOrUndefined(row[this.mainTable.uniqueId]))
            if(isNullOrUndefined(row[this.mainTable.uniqueId])){
                deleteFromVueVirtualUUID(this.mainTable.list,row.vueVirtualUUID)
            }else{
                //如果启用虚拟删除,则
                if(this.mainTable.deleteCacheHorizontalLine){
                    row.virtualChangeBitFlag= this.sksUtils.CHANGE_BIT_FLAG.delete
                    return;
                }
                deleteFromVueVirtualUUID(this.mainTable.list,row.vueVirtualUUID)
            }
        },
        /**
         * 获取存在变更的行
         */
        getNewChangeRowList(){
            getNewChangeRowList(this.mainTable.list)
        },

        renderHeader(h, args,item){
            let { column, $index }=args
            // console.log('renderHeader.h',h)
            // console.log('renderHeader.args',args)
            if(!this.mainTable.showTablePropName){
                return h('el-row',{}, [
                    h('el-col', {}, column.label ),
                ]);
            }
            return (
                <el-row>
                    <el-col>
                        {column.label}
                    </el-col>
                    <el-col>
                        <p style="display: inline;">
                            <el-tag onClick=
                                        {(e)=>clipboard(item.prop,e)}>
                                {item.prop}
                            </el-tag>
                            <el-tooltip className="item" effect="dark" content="显示更多配置" placement="top">
                                <el-button size="mini" circle icon="el-icon-search"
                                           onClick={()=>this.showPropTable(item)}
                                ></el-button>
                            </el-tooltip>
                        </p>
                    </el-col>
                </el-row>
            )
            // return h('el-row',{}, [
            //     h('el-col', {}, column.label ),
            //     h('el-col', {},[
            //         h('div',{},item.prop)
            //     ]),
            // ]);

            // return h('span', {}, [
            //     h('span', {}, column.label),
            //     h('el-popover', { props: { placement: 'top-start', width: '200', trigger: 'hover', content: '城市价格为该城市所有加盟商价格的最高价' }}, [
            //         h('i', { slot: 'reference', class:'el-icon-question'}, '')
            //     ])
            // ])
            //         <el-col>
            //         <el-popover
            //     placement="right"
            //     width="400"
            //     trigger="click">
            //         <el-table data={item}>
            //         <el-table-column width="150" property="date" label="日期"></el-table-column>
            //     <el-table-column width="100" property="name" label="姓名"></el-table-column>
            //     <el-table-column width="300" property="address" label="地址"></el-table-column>
            // </el-table>
            // <el-button slot="reference">click 激活</el-button>
            // </el-popover>
            // </el-col>
        },
        dictFormatOnElTableColumn(row, column){
            return dictFormatOnElTableColumn({
                row: row,
                column: column,
                mainTable: this.mainTable,
            })
        },
        showPropTable(item){
            this.propTableDialogInfo.data=item
            console.log("item",item)
            this.propTableDialogInfo.showDialog = true
        },
        renderHeaderCacheChangeFlagColumn(h, args){
            return (
                <el-tooltip className="item" effect="dark" content="行变更标识,根据标识会在最终[确认/提交]后进行(新增/修改/删除)数据变更处理" placement="top">
                    <i class="el-icon-question"/>
                </el-tooltip>
            )
        },

    }
}
</script>

<style scoped>
.el-table tbody tr:hover>td {
    /*background-color:#ffffff!important*/
    background-color: transparent
}
</style>
<!--
            <template slot="none-" slot-scope="{row,column,$index,item}">
            </template>
                <template slot="topBefore">
                    <div class="ml5 mr5">
                        采购清单
                    </div>
                </template>

            <sks-cache-table-el ref="sksCacheTableElRef" :visibleTop="true" :main-table="mainTable">
                <template slot="top">
                    <el-col :span="1.5">
                        <aut-button
                            type="primary"
                            icon="el-icon-plus"
                            @click="handleAdd()"
                        >新增</aut-button>
                    </el-col>
                </template>
                <template slot="none-sksOperations" slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleEditTable(scope.row)"
                    >修改</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                    >删除</el-button>
                </template>
            </sks-cache-table-el>


        handleAdd(){
            this.$refs.issueAddLineDialogRef.show2({
                form:{
                    virtualChangeBitFlag: this.sksUtils.CHANGE_BIT_FLAG.add,
                    delFlag: this.parentData?.delFlag,
                },
                dialogInfo:{
                    submitCallback:({submitData})=>{
                        console.log("submitData",submitData)
                        this.$refs.sksCacheTableElRef.addOrUpdateRow(submitData)
                        this.emitChangeSksTable()
                    },
                    location: this.form.location
                },
            })
        },
        handleEditTable(row){
            this.$refs.issueAddLineDialogRef.show({
                form: this.mergeFromObject({},row),
                dialogInfo:{
                    title: '修改',
                    submitCallback:({submitData})=>{
                        this.$refs.sksCacheTableElRef.addOrUpdateRow(submitData)
                        console.log("saleOrderBomTable.mainTable.list",this.mainTable.list)
                        console.log("saleOrderBomTable.mainTable.value",this.value)
                        this.emitChangeSksTable()
                    }
                },
            })
        },
        handleDelete(row){
            this.$refs.sksCacheTableElRef.deleteRow(row)
        },
-->

